<template>
  <base-breadcrumb>
    <div v-show="showMainForm">
      <a-card :bordered="false">
        <title-name title="基本信息"></title-name>
        <a-form-model
          ref="baseFrom"
          :model="formData.baseFrom"
          :rules="rules.baseRules"
        >
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                label="预约单位"
                prop="unitId"
              >
                <SelectCompanyAndProject
                  disabled
                  :autoSelect="true"
                  v-model="formData.baseFrom.unitId"
                  @onSelectChange="unitIdChange"
                >
                  ></SelectCompanyAndProject>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="预约部门"
                prop="reserveDeptObj"
              >
                <SelectDepartment
                  :disabled="!editable"
                  placeholder="请选择预约部门"
                  v-model="formData.baseFrom.reserveDeptObj"
                  :form="formData.baseFrom"
                  :isObj="false"
                  keyValue="unitId"
                  labelInValue
                  @change="reserveDeptChange"
                ></SelectDepartment>
                <!-- :defaultValue="{ key: currentPost.deptId, label: currentPost.deptName }" -->
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="预约人"
                prop="employeeId"
              >
                <SelectEmployees
                  :disabled="!editable"
                  ref="userRef"
                  placeholder="请选择预约人"
                  v-model="formData.baseFrom.employeeId"
                  :form="formData.baseFrom"
                  :isObj="false"
                  keyValue="reserveDeptId"
                  @change="personChange"
                ></SelectEmployees>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                label="预约人电话"
                prop="phone"
              >
                <a-input
                  :disabled="!editable"
                  placeholder="请输入预约人电话"
                  v-model="formData.baseFrom.phone"
                  allowClear
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="会议名称"
                prop="meetingName"
              >
                <a-input
                  :disabled="!editable"
                  placeholder="请输入，字数不超过50"
                  :maxLength="50"
                  v-model="formData.baseFrom.meetingName"
                  allowClear
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="会议形式"
                prop="meetingFormId"
              >
                <a-select
                  :disabled="!editable"
                  allowClear
                  v-model="formData.baseFrom.meetingFormId"
                  placeholder="请选择会议形式"
                  :options="baseData.meetingForm"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item
                label="会议级别"
                prop="meetingLevelId"
              >
                <a-select
                  :disabled="!editable"
                  allowClear
                  v-model="formData.baseFrom.meetingLevelId"
                  placeholder="请选择会议级别"
                  :options="baseData.meetingLevel"
                >
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item
                label="会议时间地点"
                prop="meetingRoomId"
              >
                <span v-if="addressAndTime">
                  {{meetAddress}}
                  <a-divider type="vertical" />
                  {{meetTime}}
                  <!-- {{(addressAndTime.datetime && addressAndTime.datetime.length) ? (addressAndTime.datetime[0] + ' - ' + addressAndTime.datetime[1].substr(11)) : ''}} -->
                </span>
                <a-button
                  v-if="editable"
                  type="primary"
                  @click="choseTimeAndAdd"
                >
                  {{addressAndTime ? '修改' : '选择'}}
                </a-button>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="是否需要签到">
                <a-radio-group
                  name="needSignGroup"
                  :disabled="!editable"
                  v-model="formData.baseFrom.isNeedSignIn"
                >
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="是否需要会议纪要">
                <a-radio-group
                  name="needJYGroup"
                  :disabled="!editable"
                  v-model="formData.baseFrom.isNeedSummary"
                >
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="是否有领导参会">
                <a-radio-group
                  name="needLeader"
                  :disabled="!editable"
                  v-model="formData.baseFrom.haveLeader"
                >
                  <a-radio :value="1">是</a-radio>
                  <a-radio :value="0">否</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item
                label="参会领导"
                prop="attendLeaderListObj"
              >
                <OrgStaffAsync
                  class="staffreadonly"
                  :class="formData.baseFrom.haveLeader == 1 ? '' : 'nohaveLeader'"
                  :disabled="!editable"
                  ref="orgStaffAsync"
                  placeholder="请选择参会领导"
                  :form="formData.baseFrom"
                  keyValue="unitId"
                  v-model="formData.baseFrom.attendLeaderListObj"
                  :selectedValue.sync="formData.baseFrom.attendLeaderListObj"
                  :isLeader="'1'"
                  :checkableAllOrgStaff="true"
                  :isLazyLoad="false"
                  @selectedObj="selectedLeaderObj"
                />
                <!-- :selectedValue.sync="objFrom.proposerId" -->
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="showSign ? 19 : 24">
              <a-form-model-item label="参会人员">
                <OrgStaffAsync
                  class="staffreadonly"
                  :disabled="!editable"
                  ref="orgStaffAsync"
                  placeholder="请选择参会人员"
                  v-model="formData.baseFrom.attendListObj"
                  :form="formData.baseFrom"
                  keyValue="unitId"
                  :selectedValue.sync="formData.baseFrom.attendListObj"
                  :isLeader="'0'"
                  :checkableAllOrgStaff="true"
                  :isLazyLoad="false"
                  @selectedObj="selectedAttendObj"
                />
              </a-form-model-item>
            </a-col>
            <a-col
              :span="5"
              v-if="showSign"
            >
              <a-button
                @click="signInVsible = true"
                style="margin-right: 10px;"
                type="primary"
              >签到明细</a-button>
              <a-button
                @click="handlePage"
                type="primary"
              >签到二维码</a-button>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="会议内容">
                <a-textarea
                  :disabled="!editable"
                  placeholder="请输入，字数不超过500"
                  :maxLength="500"
                  :rows="3"
                  v-model="formData.baseFrom.meetingContent"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>

      <a-card :bordered="false">
        <title-name title="会议服务"></title-name>
        <a-form-model
          ref="serveFrom"
          :model="formData.serveFrom"
        >
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="会议服务">
                <a-checkbox-group
                  :disabled="!editable"
                  :options="baseData.meetingServices"
                  v-model="formData.serveFrom.meetingServicesIds"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="备注">
                <a-textarea
                  :disabled="!editable"
                  placeholder="请输入，字数不超过500"
                  :maxLength="500"
                  :rows="3"
                  v-model="formData.serveFrom.remark"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-form-model-item label="附件">
                <span
                  v-if="!formData.serveFrom.fileList || formData.serveFrom.fileList.length == 0"
                  style="position: absolute;top: -2px;"
                >无</span>
                <upload-list
                  :disabled="!editable"
                  :isShow="editable"
                  :businessCode="'OF09'"
                  :uploadArrys.sync="formData.serveFrom.fileList"
                  @fileArrysData="handleFileUploaded"
                  :fileAutoLoading="false"
                  multiple
                ></upload-list>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-card>

      <!-- :disabled="type==='view'" -->
      <!-- :isShow="isShow" -->
      <ConferenceSummary
        v-if="showsummary"
        :fileObj="cursummaryFile"
        :isShow="cursummaryFile ? false : true"
        businessCode="OF10"
      ></ConferenceSummary>

      <div
        class="tool-btns page-btn-right-top"
        v-if="pageType !== 'look'"
      >
        <a-button @click="handleClose">关闭</a-button>
        <a-button
          @click="handleSave('DRAFT')"
          :loading="loading.DRAFT"
          type="primary"
        >保存草稿</a-button>
        <a-button
          @click="handleSave('SUBMITTED')"
          :loading="loading.SUBMITTED"
          type="primary"
        >提交</a-button>
      </div>
      <div
        class="tool-btns page-btn-right-top"
        v-else
      >
        <a-button @click="handleClose">关闭</a-button>
      </div>
    </div>

    <div v-show="!showMainForm">
      <ChoseRoom
        :defaultValue="addressAndTime"
        @cancel="cancelChoseRoom"
        @ok="setRoomAndTime"
      ></ChoseRoom>
    </div>

    <MeetSign
      :visible="signInVsible"
      :id="$route.query.id"
      @cancel="signInVsible = false"
      @confirm="signInVsible = false"
    ></MeetSign>
  </base-breadcrumb>
</template>
<script>
import ChoseRoom from './choseRoom.vue'
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject.vue'
import SelectEmployees from '../components/SelectEmployees.vue'
// import SelectDepartment from '@/components/Select/SelectDepartment.vue'
import SelectDepartment from '../components/SelectDepartment.vue'
import OrgStaffAsync from '../components/orgStaffAsync.vue'
import { createValidator, isPhone } from '@/utils/regExpression' // 正则校验
import UploadList from '@/components/UploadList'
import ConferenceSummary from './summary.vue'
import MeetSign from './sign.vue'
import { getLabelTypes, reservationAdd, reservationDetail, reservationEdit } from '@/api/office/anualConference/index'
import { getProjectIdFromOrg } from '@/api/commons'

export default {
  name: 'ResevationForm',
  components: {
    SelectCompanyAndProject,
    ConferenceSummary,
    SelectDepartment,
    SelectEmployees,
    OrgStaffAsync,
    UploadList,
    ChoseRoom,
    MeetSign
  },
  props: {
    // adjust:{
    //   type:Boolean,
    //   default: false
    // }
  },
  data() {
    return {
      signInVsible: false,
      currentStatus: '',
      showMainForm: true,
      currentAddAndTime: null,
      currentSummary: null,
      loading: {
        SUBMITTED: false,
        DRAFT: false
      },
      baseData: {
        meetingServices: [],
        meetingForm: [],
        meetingLevel: []
      },
      formData: {
        baseFrom: {
          unitId: '', // 预约单位id
          unitName: '', // 预约单位名称
          reserveDeptObj: {},
          reserveDeptId: '', // 预约部门id
          reserveDeptName: '', // 预约部门名称
          employeeId: undefined,
          userId: '', // 预约人ID
          userName: '', // 预约人姓名
          phone: undefined, // 预约人电话
          meetingName: '',
          meetingFormId: undefined,
          meetingLevelId: undefined,
          startTime: '',
          endTime: '',
          meetingRoomId: '',
          isNeedSignIn: 0,
          isNeedSummary: 0,
          haveLeader: 0,
          attendList: [],
          attendListObj: [],
          attendLeaderListObj: [],
          attendLeaderList: [],
          meetingContent: ''
        },
        serveFrom: {
          meetingServicesIds: [],
          remark: '',
          meetingFile: [],
          fileList: []
        },
        jiyaoFrom: {
          listUrl: '/cscec-project-business/file/constrction-progress/plan-adjust/queryFile',
          deleteUrl: '/cscec-project-business/file/constrction-progress/plan-adjust/deleteFile',
          uploadList: '/cscec-project-business/file/constrction-progress/plan-adjust/uploadFile',
          businessId: '',
          fileList: []
        }
      },
      rules: {
        baseRules: {
          phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
          reserveDeptObj: [{ required: true, message: '请选择预约部门', trigger: 'change' }],
          employeeId: [{ required: true, message: '请选择预约人', trigger: 'change' }],
          meetingFormId: [{ required: true, message: '请选择会议形式', trigger: 'change' }],
          meetingLevelId: [{ required: true, message: '请选择会议级别', trigger: 'change' }],
          meetingName: [{ required: true, message: '请填写会议名称', trigger: 'blur' }],
          meetingRoomId: [{ required: true, message: '请选择会议时间地点', trigger: 'change' }],
          attendLeaderListObj: null
        }
      }
    }
  },
  computed: {
    editable() {
      return this.$route.query.pageType !== 'look'
    },
    pageType() {
      return this.$route.query.pageType
    },
    adjust() {
      return this.$route.query.adjust
    },
    meetAddress() {
      return this.currentAddAndTime?.value?.name
    },
    meetTime() {
      const time = this.currentAddAndTime?.datetime
      // console.log(time)
      // return time && time.length ?( time[0] + ' - ' + time[1].substr(11)) : '';
      return time && time.length ? time.join(' - ') : ''
    },
    addressAndTime() {
      return this.currentAddAndTime ? this.currentAddAndTime : null
    },
    currentPost() {
      return this.$currentPost()
    },
    userInfo() {
      return this.$userInfo()
    },
    showsummary() {
      return this.pageType == 'look' && this.formData.baseFrom.isNeedSummary && (this.currentStatus === '已结束' || this.currentStatus === '进行中')
    },
    cursummaryFile() {
      return this.currentSummary
    },
    showSign() {
      return this.formData.baseFrom.isNeedSignIn == 1 && this.pageType == 'look' && this.currentStatus !== '待提交'
    }
  },
  created() {
    this.getLabelTypes(8, 'meetingForm')
    this.getLabelTypes(11, 'meetingLevel')
    this.getLabelTypes(9, 'meetingServices')

    this.initForm()

    const ADDDATA = {
      unitId: this.currentPost.id, // 预约单位id
      unitName: this.currentPost.name, // 预约单位名称
      reserveDeptObj: { key: this.currentPost.deptId, label: this.currentPost.deptName },
      reserveDeptId: this.currentPost.deptId, // 预约部门id
      reserveDeptName: this.currentPost.deptName, // 预约部门名称
      employeeId: this.userInfo.employee.id,
      userId: this.userInfo.employee.userId, // 预约人ID
      userName: this.userInfo.employee.name, // 预约人姓名
      phone: this.userInfo.employee.phone, // 预约人电话
      meetingName: '',
      meetingFormId: undefined,
      meetingLevelId: undefined,
      startTime: '',
      endTime: '',
      meetingRoomId: '',
      isNeedSignIn: 0,
      isNeedSummary: 0,
      haveLeader: 0,
      attendList: [],
      attendListObj: [],
      attendLeaderListObj: [],
      attendLeaderList: [],
      meetingContent: ''
    }

    if (this.pageType == 'add') {
      this.formData.baseFrom = ADDDATA
    } else {
      this.reservationDetail(ADDDATA)
    }
    if (this.pageType == 'adjust') {
      this.choseTimeAndAdd()
    }
  },
  watch: {
    addressAndTime: {
      handler(nv, old) {
        if (nv) {
          if (nv.datetime && nv.datetime.length > 0) {
            this.formData.baseFrom.startTime = nv.datetime[0]
            this.formData.baseFrom.endTime = nv.datetime[1]
          }
          this.formData.baseFrom.meetingRoomId = nv.value.id
        }
      },
      deep: true
    },
    'formData.baseFrom.haveLeader': {
      handler(nv, old) {
        const required = nv == 1
        this.rules.baseRules.attendLeaderListObj = [{ required: required, message: '请选择参会领导', trigger: 'change' }]
        // console.log(this.rules.baseRules.attendLeaderListObj)
      }
    }
  },
  mounted() {
    const ele = document.getElementsByClassName('ant-select-search__field')
    ele.forEach((item) => {
      item.setAttribute('readonly', 'readonly')
    })
  },
  methods: {
    reservationDetail(ADDDATA) {
      reservationDetail({ id: this.$route.query.id }).then((res) => {
        if (res && res.code == 200) {
          const newData = res.data
          const initData = JSON.parse(JSON.stringify(ADDDATA))
          for (let idx in initData) {
            initData[idx] = newData[idx]
          }
          initData.reserveDeptObj = { key: newData.reserveDeptId, label: newData.reserveDeptName }
          initData.meetingFormId = newData.meetingForm?.id
          initData.meetingLevelId = newData.meetingLevel?.id
          if (newData.meetingRoom) {
            this.currentAddAndTime = { value: newData.meetingRoom }
          }
          if (newData.startTime && newData.endTime) this.currentAddAndTime.datetime = [newData.startTime, newData.endTime]
          initData.attendLeaderListObj = newData.attendLeaderList?.map((e) => e.employeeId)
          initData.attendListObj = newData.attendList?.map((e) => e.employeeId)
          initData.isNeedSignIn = newData.isNeedSignIn ? 1 : 0
          initData.isNeedSummary = newData.isNeedSummary ? 1 : 0
          initData.haveLeader = newData.haveLeader ? 1 : 0

          // console.log(ADDDATA)
          this.formData.baseFrom = initData
          setTimeout(() => {
            this.currentSummary = newData.meetingSummaryFileInfo
            this.formData.baseFrom.employeeId = newData.employeeId
            this.currentStatus = newData.status
            this.formData.baseFrom.phone = newData.phone
          })
          this.formData.serveFrom.meetingServicesIds = newData.meetingServices.map((e) => e.id)
          this.formData.serveFrom.remark = newData.remark
          this.formData.serveFrom.fileList = newData.meetingFileInfo
          this.formData.serveFrom.meetingFile = newData.meetingFileInfo?.map((e) => e.commonId)
          // console.log(this.formData.serveFrom)
        }
      })
    },
    initForm() {
      setTimeout(() => {}, 1000)
    },
    unitIdChange($event) {
      this.formData.baseFrom.unitName = $event.name
    },
    reserveDeptChange(val) {
      if (!val) {
        this.formData.baseFrom.reserveDeptId = ''
        this.formData.baseFrom.reserveDeptName = ''
        this.formData.baseFrom.employeeId = undefined
        return
      }
      this.formData.baseFrom.reserveDeptId = val.key
      this.formData.baseFrom.reserveDeptName = val.label
    },
    personChange(val) {
      if (!val) {
        this.formData.baseFrom.userId = ''
        this.formData.baseFrom.userName = ''
        this.formData.baseFrom.phone = ''
        return
      }
      if (this.$refs.userRef && this.$refs.userRef._data && this.$refs.userRef._data.employees) {
        const objs = this.$refs.userRef._data.employees.filter((item, index) => {
          return item.id == val
        })
        let obj = objs.length ? objs[0] : {}
        this.formData.baseFrom.userId = obj.userId
        this.formData.baseFrom.userName = obj.name
        this.formData.baseFrom.phone = obj.phone
      }
    },
    selectedLeaderObj(val) {
      if (!val) return
      this.formData.baseFrom.attendLeaderList = val.map((item, index) => {
        let obj = {
          employeeId: item.id,
          userId: item.userId,
          userName: item.name,
          unitId: this.formData.baseFrom.unitId,
          unitName: this.formData.baseFrom.unitName,
          deptId: item.pId
        }
        return obj
      })
      // console.log(this.formData.baseFrom)
    },
    selectedAttendObj(val) {
      if (!val) return
      this.formData.baseFrom.attendList = val.map((item, index) => {
        let obj = {
          employeeId: item.id,
          userId: item.userId,
          userName: item.name,
          unitId: this.formData.baseFrom.unitId,
          unitName: this.formData.baseFrom.unitName,
          deptId: item.pId
        }
        return obj
      })
    },
    setRoomAndTime(obj) {
      const { value, datetime } = obj
      if (value && datetime.length) {
        this.formData.baseFrom.startTime = datetime[0]
        this.formData.baseFrom.endTime = datetime[1]
        this.formData.baseFrom.meetingRoomId = value.id
        this.currentAddAndTime = obj
        // console.log(this.currentAddAndTime)
      }
      this.cancelChoseRoom()
    },
    async getDesignEmployee() {
      try {
        const pid = this.currentPost.id
        const res = await getProjectIdFromOrg({ pid: pid, parentCodes: ['designManage'], pageNum: 1, pageSize: 100 })
        return Promise.resolve({
          status: 200,
          data: res.data.list || []
        })
      } catch (e) {
        return Promise.reject(e)
      }
    },
    getLabelTypes(type, base) {
      let param = {
        pageNo: 0,
        pageSize: 100,
        query: {
          type: type
        }
      }
      getLabelTypes(param).then((res) => {
        if (res && res.code == 200) {
          const datas = res.data.map((item, index) => {
            item.value = item.id
            item.label = item.name
            return item
          })
          this.baseData[base] = datas
        }
      })
    },
    handleFileUploaded(list) {
      this.formData.serveFrom.fileList = [...list]
      this.formData.serveFrom.meetingFile = list.map((item, index) => {
        return item.commonId
      })
    },
    choseTimeAndAdd(data = {}) {
      this.showMainForm = false
      // this.$router.push({
      //     name: 'ChoseMeetRoom',
      //     query: {
      //         pageType: this.pageType,
      //         times: this.addressAndTime ? JSON.stringify(this.addressAndTime) : ''
      //     },
      // })
    },
    handleClose() {
      this.$multiTab.close(this.$route.fullpath)
    },
    handleSave(type) {
      if (type == 'SUBMITTED') {
        this.$refs.baseFrom.validate().then((volid) => {
          if (volid) {
            this.submitForm(type)
          }
        })
      } else {
        this.submitForm(type)
      }
    },
    submitForm(type) {
      const msg = type == 'SUBMITTED' ? '提交' : '保存草稿'
      const param = {
        ...this.formData.baseFrom,
        ...this.formData.serveFrom,
        status: type
      }
      delete param.attendLeaderListObj
      delete param.attendListObj
      delete param.reserveDeptObj

      delete param.fileList
      this.loading[type] = true
      if (this.pageType == 'add') {
        reservationAdd(param)
          .then((res) => {
            this.loading[type] = false
            if (res && res.data) {
              this.$message.success(`${msg}成功`)
              this.$multiTab.close(this.$route.fullpath)
            } else {
              this.$message.success(`${msg}失败！`)
            }
          })
          .catch(() => {
            this.loading[type] = false
          })
      } else {
        param.id = this.$route.query.id
        reservationEdit(param)
          .then((res) => {
            this.loading[type] = false
            if (res && res.data && res.data.code == 200) {
              this.$message.success(`${msg}成功`)
              this.$multiTab.close(this.$route.fullpath)
            } else {
              this.$message.success(`${msg}失败！`)
            }
          })
          .catch(() => {
            this.loading[type] = false
          })
      }
    },
    cancelChoseRoom() {
      this.showMainForm = true
    },
    handlePage() {
      let routeData = this.$router.resolve({
        path: '/conference/annualConference/conferenceRoomReservation/conferenceScreen',
        query: {
          id: this.$route.query.id
        }
      })
      window.open(routeData.href, '_blank')
    }
  }
}
</script>
<style>
.nohaveLeader.ant-select:not(.ant-select-disabled) .ant-select-selection {
  border-color: #d9d9d9;
  background-color: #fff;
}
</style>
<style lang="less" scoped>
.tool-btns .ant-btn {
  margin-left: 12px;
}
.ant-form-item {
  display: flex;
}
</style>